#!/usr/bin/env python
# coding=utf-8
"""
Command Line Client For Kuaipan 

author: ksc (http://blog.geekli.cn)
api   : http://www.kuaipan.cn/developers/document.htm
"""
from __future__ import print_function

import time
import os,sys

from kplib.session import KuaipanSession
from kplib.session import log
from kplib.KuaipanAPI import KuaipanAPI
from kplib.KuaipanCLI import KuaipanCLI
from kplib.kpArgparse import kpParser

import ConfigParser
import logging 


__version='0.8.8'
__usage='''%prog [--version] [--help] <command> [<args>]'''
script_path=sys.argv[0]

parser=kpParser(__version)

if len(sys.argv) ==1 :
    parser.parse_args(['-h'])
    sys.exit()
    
args = parser.parse_args()


def get_configfile(config_file):
    
    if os.path.isabs(config_file) and os.path.isfile(config_file):
        return config_file
    files=[]    
    files.append(os.getcwd()+os.sep+config_file)
    files.append(os.path.dirname(script_path)+os.sep+config_file)
    files.append(os.path.expanduser('~')+os.sep+'.kp.ini')    
    files.append('/etc/'+'kp.ini')# not recommended

    for file in files:
        if os.path.isfile(file):
            return os.path.realpath(file)

    print('config file does not exist')
    sys.exit()

config_file=get_configfile(args.config_file)

cf = ConfigParser.ConfigParser({'root':'app_folder','log_level':'info'})
conf={}
try:
    cf.read(config_file)
    consumer_key        = cf.get("def", "consumer_key")
    consumer_secret     = cf.get("def", "consumer_secret")
    access_type=cf.get('def', 'root')
    log_level=cf.get('def', 'log_level')
        
except Exception as e:
    print('config: ',config_file)
    print('Parse config file failed')
    print(e)
    sys.exit()

#set logging    
try:
    loglevel=getattr(logging,log_level.upper())
except Exception as e:
    sys.exit( 'log_level must be one of NOTSET,DEBUG,INFO,WARNING,ERROR,CRITICAL  ')
if os.name =='posix':
    logfile='/tmp/kuaipan.log'
else:
    logfile=os.path.join(os.path.dirname(script_path),'kuaipan.log')

rlog=logging.getLogger('rlog')
rlog.setLevel(logging.DEBUG);
_streamHd = logging.StreamHandler()
_streamHd.setLevel(loglevel)
_streamHd.setFormatter(logging.Formatter('[%(name)s]%(levelname)s -- %(message)s'))
rlog.addHandler(_streamHd)


if os.access(os.path.dirname(logfile),os.W_OK):
    
    _file_handler = logging.FileHandler(logfile,'a')
    _file_handler.setLevel(logging.NOTSET)
    _file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s: %(message)s'))
    rlog.addHandler(_file_handler)
else:
    rlog.debug(logfile+' not writable')
rlog.debug( config_file)    
rlog.debug( 'consumer_key \t'+consumer_key)
#rlog.debug( 'consumer_secret:\t'+consumer_secret)

#子命令
action= args.subcommand

def _set_oauth():
    '''获取用户授权'''
    global cf,config_file,sess
    try:
        _oauth=sess.get_oauth_token()
    except KeyboardInterrupt:
        print('user press CTRL+C then exit')
        sys.exit()
    print('oauth success')
    logging.debug(_oauth)
    if not cf.has_section("oauth"):
        cf.add_section('oauth')
        
    cf.set('oauth','user_id',_oauth['user_id'])
    cf.set('oauth','oauth_token',_oauth['oauth_token'])
    cf.set('oauth','oauth_token_secret',_oauth['oauth_token_secret'])
    cf.set('oauth','expires_in',_oauth['expires_in'])
    cf.set('oauth','charged_dir',_oauth['charged_dir'])
    cf.write(open(config_file,'w'))
    
sess = KuaipanSession(consumer_key, consumer_secret,access_type)
sess.debug=False

if action =='configinfo':
    print(config_file)
    sys.exit()
    
if not cf.has_section("oauth"):
    print( 'Requires the user to authorize')
    _set_oauth()
    sys.exit()
        


rlog.debug(args)


#获取用户授权
if action=='oauth':
    _set_oauth()    
    sys.exit()

conf['oauth_token']         = cf.get("oauth", "oauth_token")
conf['oauth_token_secret']  = cf.get("oauth", "oauth_token_secret")
sess.set_oauth_token(conf['oauth_token'],conf['oauth_token_secret'])

    
api = KuaipanAPI(sess)
cli = KuaipanCLI(api)

try:
    if action in ['account_info','info']:
        print('config file:'+config_file)
        cli.info()
        
    elif action == 'mkdir':
        cli.mkdir(args.path)
        
    elif action in ['metadata','ls']:
        cli.ls(args.path,args.recursive)
        
    elif action in ['rm','delete']:
        cli.rm(args.path)
        
    elif action in ['mv','move']:
        cli.mv(args.src, args.dst)

    elif action in ['cp','copy']:
        cli.cp(args.src, args.dst)
        
    elif action in ['put','upload']:
        os.path.isfile(args.src)
        cli.put(args.src, args.dst,args.delete)

    elif action in ['get','download']:
        cli.get(args.src, args.dst)
      
    elif action in ['shares']:
        cli.shares(args.path, args.access_code)
       
    else:
        print('wrong subcommand')
        print(args)
        
except KeyboardInterrupt:
    print('user press CTRL+C then exit')
except Exception as e:
    rlog.error(e)